<script lang="ts">
	import { superForm } from '$lib/client/index.js';
	import SuperDebug from '$lib/client/SuperDebug.svelte';
	import { zod } from '$lib/adapters/zod.js';
	import { schema } from './schema.js';
	import { z } from 'zod/v3';

	export let data;

	const schema2 = z.object({
		name: z.string().min(5).trim(),
		extra: z.number()
	});

	const { validateForm, form, errors, tainted, message, enhance } = superForm(data.form, {
		taintedMessage: false,
		//dataType: 'json',
		validators: zod(schema)
	});

	async function update() {
		const result = await validateForm({ schema: zod(schema2) });
		const name: string = result.data.name;
		console.log(name);
	}
</script>

<SuperDebug data={{ $form, $errors, $tainted }} />

{#if $message}<h4>{$message}</h4>{/if}

<p id="output">NAME:{$form.name}</p>

<form method="POST" use:enhance>
	<label>
		Name: <input
			name="name"
			bind:value={$form.name}
			aria-invalid={$errors.name ? 'true' : undefined}
		/>
		{#if $errors.name}<span class="invalid">{$errors.name}</span>{/if}
	</label>
	<label>
		Email: <input
			name="email"
			bind:value={$form.email}
			aria-invalid={$errors.email ? 'true' : undefined}
		/>
		{#if $errors.email}<span class="invalid">{$errors.email}</span>{/if}
	</label>
	<div>
		<button>Submit</button>
	</div>
</form>

<button on:click={update}>Test</button>

<style lang="scss">
	form {
		margin: 2rem 0;

		input {
			background-color: #dedede;
		}

		.invalid {
			color: crimson;
		}
	}
</style>
